package com.smart.servlet;

import com.smart.dao.DBinsert;
import com.smart.domain.StudentUser;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet( name = "insertServlet",urlPatterns ="/insertServlet")
/*获取表单提交的输入的的学生信息 */
public class insertServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        request.setCharacterEncoding("UTF-8"); // 设置请求的字符编码格式，与界面的字符编码保持一致

        /*以下是获得表单提交过来的值 */
        String name = request.getParameter("name");
        String id = request.getParameter("id");
        String sex = request.getParameter("sex");
        String sclass = request.getParameter("sclass");
        String grade = request.getParameter("grade");

        /* 以下代码将获得的表单值封装到学生信息对象中 */
        StudentUser user = new StudentUser();
        user.setName(name);
        user.setId(id);
        user.setSex(sex);
        user.setSclass(sclass);
        user.setGrade(grade);
        boolean flag = DBinsert.getInstance().stuinsert(user); // 将输入的学生信息保存到数据库
        // [request.getRequestDispatcher]和[response.sendRedirect]两种请求转发的区别：
        // 前者转发时，URL地址不会改变，而后者转发时URL会发生变化。其次，前者的请求响应为同一个，而后者是重新创建新的请求与响应对象。
        if(flag){       // 当操作成功时，转发到success.html页面
            request.getSession().setAttribute("name", user.getName());
            request.getRequestDispatcher("success.html").forward(request, response);
        }else{
            response.sendRedirect("error.html");
        }
    }

}